<?php
/**
 * 本类主要完成授权后小程序相关功能
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/10/26
 * Time: 14:47
 */

namespace app\api\service;


use app\api\model\MiniAudit;
use app\lib\exception\MiniSuiteException;
use think\Request;

class MiniEvent extends Mini
{
    /**
     * 获取小程序授权后的事件与消息
     * @return mixed|string
     */
    public function getEventInfo($appid){
        $getData = Request::instance()->param();
        $postData = file_get_contents('php://input');
        $sMsg = "";  // 解析之后的明文
        $wxcpt = new \WXBizMsgCrypt( $this->token,$this->encodingAesKey,$this->appId);
        $from_xml = $this->handleXML($postData);//必须为post接收的xml格式数据
        $errCode =  $wxcpt->decryptMsg($getData['msg_signature'],$getData['timestamp'],$getData['nonce'],$from_xml,$sMsg);
        if ($errCode == 0) {
            $data =\Utils::Xml2Array($sMsg);
            $this->getEventType($data,$appid);
            return $data;
        } else {
            return  "ERR: " . $errCode . "\n\n";
        }
    }
    /**
     * 接收消息或事件的类型
     * @param $data
     */
    public function getEventType($data,$appid)
    {
        switch ($data['MsgType']){
            case 'text'://文本消息
                $this->sendServiceText($data,$content='',$appid);
                break;
            case 'image';//图片消息
                break;
            case 'miniprogrampage';//小程序卡片消息
                break;
            case 'event';//事件处理
                $this->getEvent($data,$appid);
                break;
        }
    }
    /**
     * 事件返回处理
     * @param $data
     * @param $appid
     */
    public function getEvent($data,$appid){
        error_log(print_r($data, 1), 3, "./audit.txt");
        //小程序程序审核通过
            if ($data['Event'] == 'weapp_audit_success'){
                $info['reason'] = '审核成功';
                $info['status'] = 3;//审核成功
                MiniAudit::updateAudit($info,$appid);
            }
        //小程序审核失败
            if ($data['Event'] =='weapp_audit_fail'){
                $info['reason'] = $data['Reason'];
                $info['status'] = 1;//审核失败
                MiniAudit::updateAudit($info,$appid);
            }
    }

    /**
     *发送文本消息
     * @param $data
     * @param string $content
     * @param string $appid
     */
    public function sendServiceText($data, $content = '', $appid = '')
    {

        $openid = (string)$data['FromUserName'];
        $post_data = array(
            'touser'    => $openid,
            'msgtype'   => 'text',
            'text' => array(
                'content'   => $content
            )
        );
        if ($data['ToUserName'] == 'gh_8dad206e9538'){
            $query_auth_code = preg_replace("/QUERY_AUTH_CODE:/", "", $data['Content']);
            $post_data['text']['content'] = $query_auth_code.'_from_api';
            $this->sendMessages($query_auth_code,$post_data,$type = 1);
        }else{
            $this->sendMessages($appid,$post_data,$type = 2);
        }

    }
    /**
     * 发送消息
     * @param $appid
     * @param $data
     * @return bool
     * @throws MiniSuiteException
     */
    public function sendMessages($query_auth_code,$data,$type){
        if ($type == 1){
            $access_token = $this->getQueryAuthCode($query_auth_code);
        }else{
            $access_token = $this->getAcessTokenValue($query_auth_code);
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s';
        $url = sprintf($url,$access_token);
        $requestData = curl_post($url,$data);
        $info = json_decode($requestData);
        if ($info->errcode == 0){
            return true;
        }else{
            throw new MiniSuiteException([
                'msg'=>'发送消息失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }

    /**
     *回复文本消息格式
     * @param $object
     * @param $content
     * @return string
     */
    private function responseText($data,$content){
        if (!isset($content) || empty($content)){
            return "";
        }
        $xmlTpl =   "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[text]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                    </xml>";
        $result = sprintf($xmlTpl, $data['FromUserName'], $data['ToUserName'], time(), $content);
        return $result;
    }

    /**
     * 获取授权信息（全网发布时用）
     * @param $query_auth_code
     * @return mixed
     */
    private function getQueryAuthCode($query_auth_code){
        $componentAccessToken = $this->getComponentValue();//获取component_access_token
        $query_auth_code =  $query_auth_code = preg_replace("/queryauthcode@@@/", "", $query_auth_code);
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=%s';
        $url = sprintf($url,$componentAccessToken);
        $params = [
            'component_appid'=>$this->appId,
            'authorization_code'=>$query_auth_code,
        ];
        $requsetData = curl_post($url,$params);//请微信接口获取凭据和授权信息
        $data = json_decode($requsetData);
        if (property_exists($data,'authorization_info')){
            $authorization_info = $data->authorization_info;
            $authorizer_access_token = $authorization_info->authorizer_access_token;//授权方的access_token
            return $authorizer_access_token;
        }
    }
    /**
     * 获取access_token
     * @param $uid
     * @return bool|mixed
     */
    private function getAcessTokenValue($appid){
        if (cache($appid)){
            $access_token = json_decode(cache($appid));
        }else{
            $mini = new Mini();
            $access_token =  $mini->getAccessToken($appid);
        }
        return $access_token;
    }
}